package com.sanbi.erp.api.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * @Desc:
 * @Data: 2022/7/26 15:29
 * @Author: jxk
 */
@Slf4j
public class Base64Util {


    /**
     * base64转图片
     */
    public static void base64Str2Jpg(String base64,String targetPath){
        File file = null;
        FileOutputStream fops = null;
        base64 = base64.replace("data:image/jpeg;base64,","");
        byte[] buff = DatatypeConverter.parseBase64Binary(base64);
        try {
            fops = new FileOutputStream(new File(targetPath));
            fops.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("ok");

    }

    /**
     * Base64字符串转pdf文档
     *
     * @param str
     * @param fileName
     */
    public static void base64Str2Pdf(String str, String fileName) {
        FileOutputStream fop = null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedBytes = new byte[0];
        try {
            decodedBytes = decoder.decodeBuffer(str);
            File file = new File(fileName);
            ;
            fop = new FileOutputStream(file);
        } catch (IOException e) {
            log.error("异常类型是：{}", e);
        } finally {
            if (fop != null) {
                try {
                    fop.write(decodedBytes);
                    fop.flush();
                    fop.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 编码
     *
     * @param str
     * @return
     */
    public static String encode(final String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return Base64.encodeBase64String(str.getBytes());
    }

    /**
     * 编码2
     *
     * @param bytes
     * @return
     */
    public static String encode2(byte[] bytes) {

        return Base64.encodeBase64String(bytes);
    }


    /**
     * @param strBase64 : 文件的base64字符串转字节数组
     */
    public static byte[] base64ToFileByte(String strBase64) {
        return java.util.Base64.getDecoder().decode(strBase64);
    }




    public static void main(String[] args) throws Exception {
      //  System.out.println(encode2(MD5Util.md("{\"billCodes\":\"UT0000352320970\"}a0a1047cce70493c9d5d29704f05d0d9")));


    }

}
